import copy

from bs4 import BeautifulSoup

import Stock_Function as s_f


# 股票指标
class Stock_Index:
    # 股票数据
    data_type_info = {}
    # 是否删除下载的csv 1删除 0不删除
    is_del_csv = 0
    # 临时保存数据（存进数据库之前）
    save_data = {}
    # 临时年份
    years = {}
    # 数据库连接
    mysql_conn = None

    def run(self):
        print("股票信息", self.data_type_info["code"], self.data_type_info["stock_name"])
        self.years = {}
        self.save_data = {}
        # 获取网页数据
        for info_key in self.data_type_info["html"]:
            self.get_html_data(info_key)
            pass
        # 获取csv数据
        self.get_csv_data()
        # print(self.save_data)
        # print("获取数据结束，开始写入数据库")
        s_f.write_mysql(self.data_type_info["code"], self.save_data, self.mysql_conn)
        # print("写入数据库结束")

    # 获取 预付款项、应收票据及应收账款
    # 检查数据里是否存在年份
    def check_years(self, years, is_csv):
        save_data_key = {
            "gm": 0,
            "operating_profit_margin": 0,
            "profit_margin": 0,
            "roe": 0,
            "free_cash_flow": 0,
            "gross_revenue": 0,
            "net_profit": 0,
            "advance_charge": 0,
            "receivable": 0,
        }
        if not bool(self.save_data):
            for year in range(len(years)):
                if is_csv == 0:
                    self.save_data.update({years[year].contents[0]: copy.copy(save_data_key)})
                    self.years[year] = years[year].contents[0]
                else:
                    self.save_data.update({years[year]: copy.copy(save_data_key)})
                    self.years[year] = years[year]

    # 获取网页数据
    def get_html_data(self, data_type):
        # 数字表示该数值在网页表格中的索引
        html_info = self.data_type_info["html"]
        html_code, html_body = s_f.curl_data(html_info[data_type]["url"])
        if html_code == 200:
            soup = BeautifulSoup(html_body, features="lxml")
            inner_box = soup.find("div", class_="inner_box")
            tr_all = inner_box.find("table", class_="table_bg001 border_box limit_sale scr_table").findAll("tr")
            # 年份
            self.check_years(tr_all[0].findAll("th"), 0)
            # 分析填入读取数据
            data_info = html_info[data_type]["info"]
            for d_key in data_info:
                # 如果索引是算式则计算
                if isinstance(data_info[d_key], list):
                    for y_key in range(len(self.save_data)):
                        # 获取算式
                        result = 0
                        s_symbol = ""
                        for d_k_s in data_info[d_key]:
                            if s_f.is_number(d_k_s):
                                td_data = tr_all[d_k_s].findAll("td")
                                if result == 0:
                                    result = s_f.str_to_float(td_data[y_key].contents[0])
                                else:
                                    result = s_f.math_ting(result, s_f.str_to_float(td_data[y_key].contents[0]),
                                                           s_symbol)
                            else:
                                s_symbol = d_k_s
                        self.save_data[self.years[y_key]][d_key] = result
                else:
                    td_data = tr_all[data_info[d_key]].findAll("td")
                    td_data_num = len(td_data)
                    for y_key in range(len(self.years)):
                        if y_key < td_data_num:  # 有些数据缺少就跳出
                            self.save_data[self.years[y_key]][d_key] = s_f.str_to_float(td_data[y_key].contents[0])
        else:
            print(html_info[data_type]["url"], "获取失败", html_code)

    # 获取csv数据

    def get_csv_data(self):
        csv_details = self.data_type_info["csv"]
        for csv_info_key in csv_details:
            csv_info = csv_details[csv_info_key]["info"]
            # 下载csv文件到temp并返回
            csv_temp_name = csv_info_key + self.data_type_info["code"] + "Index"
            url = csv_details[csv_info_key]["url"]
            path, status_code = s_f.down_csv(url, csv_temp_name)
            if status_code == 200:
                csv_rows = s_f.open_csv(path, is_del=self.is_del_csv)  # 读取文件
                self.check_years(csv_rows[0], is_csv=1)  # 判断年份是否存在
                for type_key in csv_info:
                    # 如果需要计算时再写
                    if isinstance(csv_info[type_key], list):
                        pass
                    else:
                        for y_key in range(len(self.years)):
                            csv_rows_num = len(csv_rows)
                            if y_key < csv_rows_num:  # 有些数据缺少就跳出
                                self.save_data[self.years[y_key]][type_key] = s_f.str_to_float(
                                    csv_rows[csv_info[type_key]][y_key])

            else:
                print(status_code, self.data_type_info["code"] + csv_info_key + "csv获取失败", url)
